$(function () {
    const layer = layui.layer
    const form = layui.form
    const laypage = layui.laypage
    laypage.render({
        elem: 'pager',
        count: 50,
        layout: ['count', 'limit', 'prev', 'page', 'next', 'skip']
    })
    renderCate()
    const query = {
        pagenum: 1, // 当前页码
        pagesize: 5, // 每页条数
        cate_id: '',
        state: ''
    }


    function renderCate() {
        $.get('/my/article/cates').then(res => {
            $('select[name=cate_id]').html(template('tpl-cate', res))
            form.render()
        })
    }
    renderArticle()

    function renderArticle() {
        $.get('/my/article/list', query).then(res => {
            const total = res.total
            $('tbody').html(template('tpl-list', res))
            laypage.render({
                elem: 'pager',
                count: total,
                limit: query.pagesize, //每页数量
                limits: [2, 5, 10, 15, 20, 50], //条数切换
                curr: query.pagenum, // 当前页码
                layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
                jump: function (obj, first) {
                    query.pagenum = obj.curr
                    query.pagesize = obj.limit
                    if (!first) {
                        renderArticle()
                    }
                }
            })
        })
    }

    $('#filter-form').on('submit', function () {
        const data = form.val('filter-form')
        query.cate_id = data.cate_id
        query.state = data.state
        renderArticle()
        return false
    })

    $('tbody').on('click', '.btn-delete', function () {
        layer.confirm('你确定要删除吗？', {
            title: '提示',
            icon: 3
        }, index => {
            const id = $(this).data('id')
            const len = $('.btn-delete').length
            $.get('/my/article/delete/' + id).then(res => {
                if (res.status !== 0) {
                    return layer.msg('删除失败')
                }
                layer.msg('删除成功')
                if (len <= 1) {
                    query.pagenum = query.pagenum == 1 ? 1 : query.pagenum - 1
                }
                renderArticle()
            })

            layer.close(index)
        })
    })

    $('tbody').on('click', '.preview-link', function () {
        const id = $(this).data('id')
        $.get('/my/article/' + id).then(res => {
            console.log(res);
            layer.open({
                title: '文章预览',
                type: 1,
                area: ['85%', '85%'],
                content: template('tpl-preview', res)
            })
        })
    })
})